<?php

namespace App\Http\Controllers\Api;

use App\Repositories\Api\MemberMatchRepository;
use App\Repositories\Api\MemberRepository;
use App\Repositories\Api\EnlistRepository;
use App\Repositories\Api\ElectPoolJoinRepository;
use App\Repositories\Api\PyqPostRepository;
use App\Repositories\Api\WechatMenusRepository;
use App\Repositories\OrderRepository;

use App\Models\Order;
use App\Models\EnlistWeixin;

use App\Models\Enlist;

use App\Models\KeywordRecord;
use App\Models\AccountRecord;

use Exception;
use Cache;

class EnlistController extends MiniAppController
{
    private $memberRep = NULL,
        $enlistRep = NULL,
        $orderRep = NULL;

    public function __construct(
        MemberRepository      $memberRep,
        EnlistRepository      $enlistRep,
        WechatMenusRepository $wechatMenusRep,
        OrderRepository       $orderRep
    )
    {
        parent::__construct();
        $this->memberRep = $memberRep;
        $this->enlistRep = $enlistRep;
        $this->orderRep = $orderRep;

        $this->wechatMenusRep = $wechatMenusRep;
    }

    /**
     * 初始应征数据
     * @Author   thomashtao               bosslen
     * @DateTime 2022-04-20T10:35:19+0800
     * @return   [type]                   [description]
     */
    public function init_data()
    {
        $df_uid = intval(request()->get("id"));
        $enlist_price = $this->enlistRep->get_enlisted_float_price($df_uid);
        $is_need_recharge = $this->memberRep->check_account_balance(UID, $enlist_price);

        //  判断应征
        $df_member = $this->memberRep->getOne($df_uid);
        if ($df_member['cancel'] == 0) {
            (new MemberMatchRepository())->del(UID, $df_uid);
            return retFail("对方账户已注销，不允许查看");
        }

        (new MemberMatchRepository())->updateVisitTime(UID, $df_uid);

        $stepby = $this->memberRep->check_member_profile(true, false);
        $member = $this->memberRep->getSimpleMember(UID, 3);

        $lcity = '不限';
        if ($member['lcity'] && is_str_has($member['lcity'], '市')) {
            $lcity = str_replace('市', '', $member['lcity']);;
        }
        $elected = Enlist::whereRaw("(enlist_uid =" . UID . " and enlisted_uid=$df_uid) or (enlisted_uid =" . UID . " and enlist_uid=$df_uid)")->orderBy("id", "desc")
            ->first();

//        $elected['status'] != 1 && $extra_ids = "3";
        $categories = $this->wechatMenusRep->getMemberCategoryForMember();
        $fields = $this->memberRep->getMemberFields();

        if ($member['Latitude'] && $member['Longitude'] && $df_member['lcity']) {
            $show_city = ($df_member['lcity'] == $member['lcity']) ? $df_member['ldistrict'] : $df_member['lcity'];
            $df_member['jw_location'] = get_distance($member['Latitude'], $member['Longitude'], $df_member['Latitude'], $df_member['Longitude']) . $show_city;
        }

        // 检查是否获取微信了
        $is_get_wx = EnlistWeixin::where(['enlist_uid' => UID, 'enlisted_uid' => $df_member['id']])->count("id");
        if (!$is_get_wx) {//是否被获取
            $ew_count = EnlistWeixin::where(['enlisted_uid' => UID, 'enlist_uid' => $df_member['id']])->count("id");
            $is_get_wx = $ew_count > 0 ? 2 : 0;
        }
        $result['is_get_wx'] = $is_get_wx ?? 0;

        $df_member = member_detail_data($df_member, ($is_get_wx == 1 || (!empty($elected) && $elected['status'] == 1)) ? true : false);//过滤数据

        $result['enlist_price'] = $enlist_price;
//        $result['is_need_recharge'] = $is_need_recharge;
        $result['fields'] = $fields;
        $result['stepby'] = $stepby;
        $result['elected'] = $elected;
        $result['categories'] = $categories;
        $result['df_member'] = $df_member;
        $result['weixin_price'] = self::WEIXIN_PRICE;
        $result['member'] = $member;

        return retSuc($result);
    }

    public function index()
    {
        $type = request()->get("type", "");

        switch ($type) {
            case "suc":// 相互喜欢的
                $filter['status'] = 1;
                $filter['enlist_uid'] = UID;
                break;
            case "enlistor": //喜欢我的
                $filter['enlisted_uid'] = UID;
                $filter['status'] = intval(request()->get("status", 0));
                break;
            case "my"://我喜欢的
                $filter['enlist_uid'] = UID;
                break;
        }
        $res = $this->enlistRep->getLists($filter, $this->pageSize, $this->pageNum);
        if ($this->pageNum == 1) {
            $res['member'] = $this->memberRep->getSimpleMember(UID, 2);
        }
        return $this->apiResponse->success($res);
    }

    /**
     * 应征详情
     * @Author   thomashtao               bosslen
     * @DateTime 2022-07-03T21:56:04+0800
     * @return   [type]                   [description]
     */
    public function detail()
    {
        $id = intval(request()->get("id", 0));
        $enlist = $this->enlistRep->getOne($id);
        if (empty($enlist))
            return $this->apiResponse->error("应征记录不存在");

        if (empty(Enlist::where("id", "=", $id)->value("see_time"))) {
            Enlist::where("id", "=", $id)->update(['see_time' => date('Y-m-d H:i:s')]);
        }

        $uid = $enlist['enlisted_uid'] == UID ? $enlist['enlist_uid'] : $enlist['enlisted_uid'];
        $enlist_member = $this->memberRep->getSimpleMember($uid, 2, $enlist['status'] == 1 ? true : false);
        $return = [
            'enlist' => $enlist,
            'member' => $enlist_member,
            'is_enlist' => ($enlist['enlisted_uid'] == UID ? 1 : 2)
        ];

        if ($enlist['enlist_uid'] == UID) {
            $member = $this->memberRep->getOne(UID);

            $return['enlist_member'] = $member;
            $enlist_amount = Enlist::where([
                'enlist_uid' => UID,
                'enlisted_uid' => $enlist['enlisted_uid'],
            ])->count("id");

            $enlist_price = $this->enlistRep->get_enlist_price($member, $enlist_member);
            $return['enlist_price'] = $enlist_price * ($enlist_amount + 1);
        }

        // is_enlist 1: 应征我的 2：我应征的
        return $this->apiResponse->success($return);
    }

    public function member()
    {
        $id = intval(request()->get("id", 0));
        $enlist_id = intval(request()->get("enlist_id", 0));
        $enlist = $this->enlistRep->getOne($enlist_id);

        if (!$enlist)
            return $this->apiResponse->error("应征记录不存在");
        if (!in_array(UID, [$enlist['enlist_uid'], $enlist['enlisted_uid']]))
            return $this->apiResponse->error("应征记录不存在");

        $df_uid = $enlist['enlist_uid'] == UID ? $enlist['enlisted_uid'] : $enlist['enlist_uid'];
        $enlist_member = $this->memberRep->getOne($df_uid);
        if ($enlist['status'] == 1) { //应征成功-显示联系方式
            $enlist_member = member_detail_data($enlist_member, true);//过滤敏感数据
        } else { //不显示联系方式
            $enlist_member = member_detail_data($enlist_member);//过滤敏感数据
        }
        $enlist_member['enlist'] = $enlist;
        $member = $this->memberRep->getOne(UID);
        if (empty(Enlist::where("id", "=", $enlist['id'])->value("see_time"))) {
            Enlist::where("id", "=", $enlist['id'])->update(['see_time' => date('Y-m-d H:i:s')]);
        }

        if (!in_array(UID, [5, 26534, 1882, 16272]) && $enlist_member['id'] != $member['id'] && $enlist_member['gender'] == $member['gender']) {
            return $this->apiResponse->error("只能访问异性资料哦！", 400);
        }

        if (trim($enlist_member['education']) == '博' && $enlist_member['doctor_college'] != null) {
            $school_name = $enlist_member['doctor_college'];
        } elseif (trim($enlist_member['education']) == '硕' && $enlist_member['master_college'] != null) {
            $school_name = $enlist_member['master_college'];
        } else {
            $school_name = $enlist_member['undergraduate'];
        }

        if ($member['Latitude'] && $member['Longitude'] && $enlist_member) {
            $enlist_member['jw_location'] = get_distance($member['Latitude'], $member['Longitude'], $enlist_member['Latitude'], $enlist_member['Longitude']);
        }

        $extra_ids = "7,10,11,12";
        //应征未成功去掉联系方式
        if ($enlist['status'] != 1) {
            $extra_ids .= ",3";
        }

        $categories = (new WechatMenusRepository())->getMemberCategoryForMember();
        $fields = $this->memberRep->getMemberFields();
        $member = $this->memberRep->getSimpleMember(UID, 2);


        return $this->apiResponse->success(compact(
            "enlist_member",
            "categories",
            "fields",
            "member"
        ));
    }

    /**
     * 删除应征记录
     * @Author   thomashtao               bosslen
     * @DateTime 2022-03-15T10:09:29+0800
     * @param string $value [description]
     * @return   [type]                           [description]
     */
    public function delete($value = '')
    {
        $enlist_id = intval(request()->post("enlist_id"));
        $wechat_admin_id = request()->get("wechat_admin_id");
        $enlist = $this->enlistRep->getOne($enlist_id);

        if (!$enlist)
            return $this->apiResponse->error("应征记录不存在", 400);

        if ($enlist['enlist_uid'] != $wechat_admin_id)
            return $this->apiResponse->error("无权限", 400);

        $this->enlistRep->delete($enlist_id);
        return $this->apiResponse->success([], "删除成功");
    }

    /**
     * 接受/拒绝应征
     * @Author   thomashtao               bosslen
     * @DateTime 2022-03-15T11:36:51+0800
     * @return   [type]                   [description]
     */
    public function accept()
    {
        $enlist_uid = intval(request()->post("euid"));
        $status = intval(request()->post("status"));
        $wechat_admin_id = request()->get("wechat_admin_id");

        $params = request()->all();
        if (!$params['euid'] && empty($params['enlist_id']))
            return retFail("参数不对，请稍后再试");

        $enlist = $this->enlistRep->getOne($params['enlist_id']);
        if (empty($enlist))
            return retFail("参数不对，请稍后再试");

        if ($enlist['status'] != 0)
            return retFail("申请记录不存在");

        if ($enlist['enlisted_uid'] != UID)
            return retFail("无权限");

        if (!in_array($status, [1, 2]))
            return retFail("异常操作");

        if ($status == 1) { //接受
            $this->enlistRep->updateFields($enlist['id'], [
                'status' => 1,
                'enlist_time' => date('Y-m-d H:i:s')
            ]);

            $enlist_member = $this->memberRep->getSimpleMember($enlist['enlist_uid'], 3);
            $member = $this->memberRep->getOne(UID, 3);

            //需要审核信息
            /*sendTemplateMsg($enlist_member['openid'], 3, [
                'object_id' => $enlist['id'],
                'object_type' => 'enlist',
                'wo_uid' => $member['id'],
                'df_uid' => $enlist_member['id'],
                'content' => $member['id'] . $member['username'] . '接受了你的应征。',
                'uid' => $member['id'],
                'username' => $member['username'],
                'page' => "enlist/index"
            ], 6);*/
            return retSuc([
                'weixin' => $enlist_member['weixin'],
                'weixin_qrcode_path' => $enlist_member['weixin_qrcode_pic']
            ]);
        } else if ($status == 2) { //拒绝

            Enlist::where("id", "=", $enlist['id'])->update([
                'status' => 2,
                'enlist_time' => date('Y-m-d H:i:s')
            ]);

            $account_record = AccountRecord::where(['orderid' => $enlist['order_id']])->first();
            if ($account_record) {
                $refund_price = 0;

                if ($account_record['amount_perm'] > 0) {//永久金额
                    //变更账户余额，并记录
                    $amount_perm = bcdiv($account_record['amount_perm'], 2, 2);
                    $refund_price = $refund_price + $amount_perm;
                    $this->memberRep->change_user_account($enlist_uid, $wechat_admin_id, null, 1, $amount_perm, $account_record['orderid'], 1);
                }

                if ($refund_price > 0) {
                    //退款更新订单
                    Order::where(['id' => $account_record['orderid']])->update([
                        'status' => 70,
                        'refund_price' => $refund_price,
                        'refund_time' => date("Y-m-d H:i:s")
                    ]);
                }

            }

        } else {
            return $this->apiResponse->error("无效操作", 400);
        }
        return $this->apiResponse->success([], "ok");
    }

    /**
     * 拒绝应征
     * @Author   thomashtao               bosslen
     * @DateTime 2022-03-29T13:33:08+0800
     * @return   [type]                   [description]
     */
    public function refuse()
    {

        $enlist_uid = intval(request()->post("euid"));
        $reason = request()->post("reason");
        $select_reason = intval(request()->post("type"));

        $wechat_admin_id = request()->get("wechat_admin_id");
        $enlist = Enlist::where([
            'enlisted_uid' => UID,
            'enlist_uid' => $enlist_uid,
            'status' => 0,
            'is_delete' => 1,
        ])->first();
        if (!$enlist) {
            return $this->apiResponse->error("应征记录不存在", 400);
        }

        $this->accept();

        $enlist_member = $this->memberRep->getOne($enlist_uid);
        $member = $this->memberRep->getOne($wechat_admin_id);
        $account = $this->memberRep->get_account($enlist_member['id']);

        $info['select_reason'] = refuse_reason($select_reason);
        $info['reason'] = $reason ?? "";
        $info['status'] = 2;

        //应征结果提醒 需要审核信息
        /*sendTemplateMsg($enlist_member['openid'], 3, [
            'object_id' => $enlist['id'],
            'object_type' => 'enlist',
            'wo_uid' => $member['id'],
            'df_uid' => $enlist_member['id'],
            'content' => $member['id'] . $member['username'] . '拒绝了你的应征',
            'uid' => $member['id'],
            'username' => $member['username'],
            'account' => $account,
            'select_reason' => $info['select_reason'],
            'reason' => $info['reason'],
            'page' => "message/enlistor"

        ], 7);*/

        $this->enlistRep->updateFields($enlist['id'], $info);

        return $this->apiResponse->success([], 'ok');
    }

    /**
     *  确认申请认识
     * @Author   thomashtao               bosslen
     * @return   [type]                   [description]
     */
    public function confirm()
    {
        $params = request()->all();

        if (!$params['euid'])
            return retFail("参数不对，请稍后再试");

        $member = $this->memberRep->getSimpleMember(UID, 3);
        $enlist_member = $this->memberRep->getOne($params['euid']);

        if ($member['gender'] == $enlist_member['gender']) {
            return $this->apiResponse->error("只能应征异性哦", 400);
        }

        if ($params['original'] == 'weixin') {  //直接获取微信

            if (self::WEIXIN_PRICE > $member['total_account']) {
                return $this->apiResponse->error("账户余额不足，请先充值");
            }

            $enlist_amount = Enlist::where(['enlist_uid' => UID, 'enlisted_uid' => $params['euid']])->count("id");
            if ($enlist_amount > 0) {
                return $this->apiResponse->error("你已应征对方，不能重复应征哦！", 400);
            }

            $data['total_price'] = self::WEIXIN_PRICE;
            $data['title'] = "获取微信";
            $data['type'] = 11;
            $data['product_id'] = $params['euid'];
            $data['status'] = 40;
            $data['original_price'] = self::WEIXIN_PRICE;
            $data['refund_price'] = 0;

            return $this->apiResponse->success(['id' => 11]);
        }

        if (self::WEIXIN_PRICE > $member['total_account']) {
            return $this->apiResponse->error("账户余额不足，请先充值");
        }

        $enlist_amount = Enlist::where(['enlist_uid' => UID, 'enlisted_uid' => $params['euid']])->count("id");
        if ($enlist_amount > 0) {
            return $this->apiResponse->error("你已申请认识对方，不能重复申请哦！", 400);
        }

        $qr_code_id = KeywordRecord::where(['is_new' => 1, 'unionid' => $member['unionid']])->value("qr_code_id");
        if ($qr_code_id) {
            $data['resource'] = $qr_code_id;
        }

        $data['total_price'] = self::WEIXIN_PRICE;
        $data['title'] = "申请认识";
        $data['type'] = 2;
        $data['product_id'] = $params['euid'];
        $data['status'] = 40;
        $data['original_price'] = self::WEIXIN_PRICE;
        $data['refund_price'] = 0;

        $account = $member['total_account'];
        $order = $this->orderRep->generateOrder($data);

        $el_data['enlist_uid'] = UID;
        $el_data['enlisted_uid'] = $params['euid'];
        $el_data['order_id'] = $order['id'];
        $el_data['message'] = $params['content'] ?? "";
        $el_data['select_reason'] = "";
        $el_data['reason'] = "";

        try {
            $res = $this->enlistRep->updateFields(null, $el_data);

            if ($res)
                $this->memberRep->change_user_account(UID, $params['euid'], NULL, 8, self::WEIXIN_PRICE, $order['id'], 0);

            //应征结果提醒 需要审核信息
            /*
            sendTemplateMsg($enlist_member['openid'], 4, [
                  'object_id' => $res['id'],
                  'object_type' => 'enlist',
                  'wo_uid' => $member['id'],
                  'df_uid' => $enlist_member['id'],
                  'content' => $member['id'] . $member['username'] . '应征了你。',
                  'uid' => $member['id'],
                  'username' => $member['username'],
              ], 8);
              */

            return retSuc(['enlist_id' => $res['id']], "你已申请认识对方，等待对方处理");

        } catch (Exception $e) {
            return $this->apiResponse->error($e->getMessage());
        }
    }

    /**
     * 应征我的
     * @Author   thomashtao               bosslen
     * @DateTime 2022-03-29T10:28:16+0800
     * @return   [type]                   [description]
     */
    public function enlistor()
    {
        $filter['enlisted_uid'] = UID;
//        $status = request()->get("status", 0);
        $filter['status'] = [0, 1, 2];
        $res = $this->enlistRep->getLists($filter, $this->pageSize, $this->pageNum);

        if ($this->pageNum == 1) {
            $res['member'] = $this->memberRep->getOne(UID);
        }

        return $this->apiResponse->success($res);
    }

    /**
     * 再次申请应征
     * @Author   thomashtao               bosslen
     * @DateTime 2022-07-05T11:49:43+0800
     * @return   [type]                   [description]
     */
    public function reapply()
    {
        $id = intval(request()->get("id"));
        $enlist = $this->enlistRep->getOne($id);

        if (empty($enlist))
            return $this->apiResponse->error("当前应征不存在");

        if ($enlist['status'] != 2) {
            return $this->apiResponse->error("当前不可再次申请");
        }

        if ($enlist['is_apply']) {
            return $this->apiResponse->error("已再次申请过，请不要重复申请");
        }

        $enlist_member = $this->memberRep->getOne($enlist['enlisted_uid']);
        $member = $this->memberRep->getOne(UID);

        $enlist_amount = Enlist::where([
            'enlist_uid' => UID,
            'enlisted_uid' => $enlist['enlisted_uid'],
        ])->count("id");

        $enlist_price = $this->enlistRep->get_enlist_price($member, $enlist_member);
        $enlist_total_price = $enlist_price * ($enlist_amount + 1);

        if (floatval($member['total_account']) < floatval($enlist_total_price)) {
            return $this->apiResponse->error("账户余额不足，请先充值");
        }

        $data['title'] = "申请认识";
        $data['type'] = 2;
        $data['total_price'] = $enlist_total_price;
        $data['product_id'] = $enlist['enlisted_uid'];
        $data['original_price'] = $enlist_total_price;
        $data['status'] = 40;
        $data['refund_price'] = 0;
        $order = $this->orderRep->generateOrder($data);

        if ($order) {
            $this->memberRep->change_user_account(UID, $enlist['enlisted_uid'], NULL, 8, $enlist_total_price, $order['id'], 0);
        }

        $el_data['enlist_uid'] = UID;
        $el_data['enlisted_uid'] = $enlist['enlisted_uid'];
        $el_data['original_enlist_id'] = $enlist['id'];
        $el_data['order_id'] = $order['id'];
        $el_data['message'] = request()->get("content");
        $el_data['from'] = request()->get("from");
        $el_data['select_reason'] = "";
        $el_data['reason'] = "";

        try {
            $res = $this->enlistRep->updateFields(null, $el_data);
            //应征结果提醒 需要审核信息
            sendTemplateMsg($enlist_member['openid'], 4, [
                'object_id' => $res['id'],
                'object_type' => 'enlist',
                'wo_uid' => $member['id'],
                'df_uid' => $enlist_member['id'],
                'content' => $member['id'] . $member['username'] . '应征了你。',
                'uid' => $member['id'],
                'username' => $member['username'],
            ], 8);

            return $this->apiResponse->success(['enlist_id' => $res['id']], "你已应征对方，等待对方处理");
        } catch (Exception $e) {
            return $this->apiResponse->error($e->getMessage());
        }
    }

    /**
     * 超级喜欢
     */
    public function add_super()
    {
        $df_uid = intval(request()->post("df_uid"));
        return $this->enlistRep->addSuper($df_uid, self::SUPER_PRICE);
    }

    /**
     * 获取微信
     *
     * @Author   thomashtao               bosslen
     * @DateTime 2022-09-23T14:45:00+0800
     * @return   [type]                   [description]
     */
    public function weixin()
    {
        $params = request()->only("euid", "original");

        if (!$params['euid'])
            return $this->apiResponse->error("参数不对，退出重新进入应征页面", 400);

        $member = $this->memberRep->getSimpleMember(UID, 2);
        $enlist_member = $this->memberRep->getOne($params['euid']);

        if ($member['gender'] == $enlist_member['gender']) {
            return $this->apiResponse->error("只能应征异性哦", 400);
        }

        if (self::WEIXIN_PRICE > $member['total_account']) {
            return $this->apiResponse->error("账户余额不足，请先充值");
        }
        $enlist_amount = Enlist::where(['enlist_uid' => UID, 'enlisted_uid' => $params['euid']])->count("id");
        if ($enlist_amount > 0) {
            return $this->apiResponse->error("你已应征对方，不能重复应征哦！", 400);
        }

        //检查重复获取
        if (EnlistWeixin::where(['enlist_uid' => UID, 'enlisted_uid' => $enlist_member['id']])->count()) {
            return $this->apiResponse->success(['msg' => "已获取微信，请不要重复获取"]);
        }

        $data['total_price'] = self::WEIXIN_PRICE;
        $data['title'] = "我要应征-获取微信";
        $data['type'] = 3;
        $data['product_id'] = $params['euid'];
        $data['status'] = 40;
        $data['original_price'] = self::WEIXIN_PRICE;
        $data['refund_price'] = 0;

        if ($member['total_account'] != 0) {
            $real_pay = get_real_pay($member['total_account'], $data['total_price']);
            $dikou = get_dikou($member['total_account'], $data['total_price']);
            $data['total_price'] = $real_pay;
        }

        $order = $this->orderRep->generateOrder($data);
        if (!$order)
            return $this->apiResponse->error("获取失败");

        $res = EnlistWeixin::create([
            'enlisted_uid' => $params['euid'],
            'enlist_uid' => UID,
            'price' => self::WEIXIN_PRICE,
            'orderid' => $order['id']
        ]);

        $this->memberRep->change_user_account(UID, $params['euid'], NULL, 51, self::WEIXIN_PRICE, $order['id'], 0);

        //增加微信通知模版
        sendTemplateMsg($enlist_member['openid'], 17, [
            'object_id' => $res['id'],
            'object_type' => 'getweixin',
            'wo_uid' => $member['id'],
            'df_uid' => $enlist_member['id'],
            'content' => $member['id'] . $member['username'] . '对你超级心动',
            'uid' => $member['id'],
            'username' => $member['username'],
            'page' => "nearby/member?id=" . $member['id']
        ], 15);

        return retSuc([
            'id' => $res['id'],
            'weixin' => $enlist_member['weixin'] ?? '',
            'weixin_qrcode_pic' => $enlist_member['weixin_qrcode_pic'] ?? ''
        ]);
    }

}